package com.example.demo.slidingwindow;

import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Data
public class SlidingWindowQueueService {
    //线程安全的队列
    private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(10);
    //每次窗口大小
    private AtomicInteger count = new AtomicInteger(1);

    @PostConstruct
    @SneakyThrows
    public void execute(){
        while(true){
            if(count.incrementAndGet() == 0){
                Thread.sleep(1000);
            }else{
                Runnable poll = queue.poll();
                if(poll != null){
                    poll.run();
                    count.decrementAndGet();
                }
            }
        }

    }
}
